var pageIndex;
var pageSize;
var searchName = '';
// 获取所有数据和总记录数 { total: 100, data: [...] }
var dataResult = null;
mini.parse();
var grid = mini.get('userGrid');

var Sexs = [{ id: 1, text: '男' }, { id: 2, text: '女' }];

//根据后台的数据，返回性别
function onSexRenderer(e) {
    for (var i = 0, l = Sexs.length; i < l; i++) {
        var g = Sexs[i];
        if (g.id == e.value) return g.text;
    }
    return "";
}

function getUserList(pageIndex, pageSize, searchName) {
    $.ajax({
        url: GatewayUrl() + '/user/list',
        type: 'get',
        async: false,
        data: {
            "pageIndex": pageIndex,
            "pageSize": pageSize,
            "searchName": searchName
        },
        headers: {
            "Authorization": localStorage.getItem("token")
        },
        success: function (dt) {
            if (dt.code === 200) {
                dataResult = mini.decode(dt.data);
            }
        }
    })
}

$(function () {
    pageIndex = 0;
    pageSize = 6;
    getUserList(pageIndex + 1, pageSize, searchName);
    fillData(0, grid.getPageSize(), dataResult, grid);
})

// 分页填充细节处理
function fillData(pageIndex, pageSize, dataResult, grid) {

    var data = dataResult.data, totalCount = dataResult.total;

    var arr = [];
    var start = pageIndex * pageSize, end = start + pageSize;
    for (var i = 0; i < dataResult.data.length; i++) {
        arr.push(dataResult.data[i]);
    }
 

    grid.setTotalCount(totalCount);
    grid.setPageIndex(pageIndex);
    grid.setPageSize(pageSize);

    grid.setData(arr);
}

// 监听分页前事件，阻止后自行设置当前数据和分页信息
grid.on("beforeload", function (e) {
    e.cancel = true;
    pageIndex = e.data.pageIndex, pageSize = e.data.pageSize;
    getUserList(pageIndex + 1, pageSize, searchName);
    fillData(pageIndex, pageSize, dataResult, grid);
});

//操作，重置密码、启用停用账号
function onActionRenderer(e) {
    var grid = e.sender;
    var record = e.record;
    var uuid = record.uuid;
    var rowIndex = e.rowIndex;

    var html = '<a class="New_Button" href="javascript:resetPwd(' + uuid + ')">重置密码</a> ';
    var item;

    if (record.status === 1) {
        item = '<a class="New_Button" style="color:red;" href="javascript:stopStatus(' + uuid + ')">停用</a>';
    } else {
        item = '<a class="New_Button" style="color:green;" href="javascript:startStatus(' + uuid + ')">启用</a>';
    }
    html += item;
    return html;
}

//启用账号
function startStatus(uuid) {
    mini.confirm("确定启用？", "确定？",
        function (action) {
            if (action == "ok") {
                $.ajax({
                    url: GatewayUrl() + "/user/updateStatus/" + uuid,
                    type: 'put',
                    data: {
                        "status": 1
                    },
                    headers: {
                        "Authorization": localStorage.getItem("token")
                    },
                    success: function (dt) {
                        if (dt.code === 200) {
                            refresh('账号已启用');
                        }
                    }
                })
            }
        }
    )
}

//停用账号
function stopStatus(uuid) {
    mini.confirm("确定停用？", "确定？",
        function (action) {
            if (action == "ok") {
                $.ajax({
                    url: GatewayUrl() + '/user/updateStatus/' + uuid,
                    type: 'put',
                    data: {
                        "status": 2
                    },
                    headers: {
                        "Authorization": localStorage.getItem("token")
                    },
                    success: function (dt) {
                        if (dt.code === 200) {
                            refresh('账号已停用');
                        }
                    }
                })
            }
        }
    )
}


function refresh(content) {
    mini.showTips({
        content: content,
        state: 'success',
        x: 'Center',
        y: 'Top',
        timeout: 3000
    });
    getUserList(pageIndex + 1, pageSize, searchName);
    fillData(pageIndex, grid.getPageSize(), dataResult, grid);
}

//重置密码
function resetPwd(uuid) {
    mini.confirm("确定重置密码？", "确定？",
        function (action) {
            if (action == "ok") {
                $.ajax({
                    url: GatewayUrl() + '/user/resetPwd/' + uuid,
                    type: 'put',
                    headers: {
                        "Authorization": localStorage.getItem("token")
                    },
                    success: function (dt) {
                        if (dt.code === 200) {
                            mini.showTips({
                                content: "密码重置为 111111",
                                state: 'success',
                                x: 'Center',
                                y: 'Top',
                                timeout: 3000
                            });
                        }
                    }
                })
            }
        }
    )
}

//回车键
function onKeyEnter(e) {
    search();
}

//搜索
function search() {
    searchName = mini.get("searchName").getValue();
    if (searchName !== '') {
        getUserList(pageIndex + 1, pageSize, searchName);
        fillData(0, grid.getPageSize(), dataResult, grid);
    } else {
        searchName = '';
        getUserList(pageIndex + 1, pageSize, searchName);
        fillData(0, grid.getPageSize(), dataResult, grid);
    }
}


//编辑
function edit() {
    var row = grid.getSelected();
    if (row) {
        mini.open({
            url: BaseUrl() + "/admin/user/addUpdate.html",
            title: "编辑用户", width: 600, height: 400,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { action: "edit", uuid: row.uuid };
                iframe.contentWindow.SetData(data);

            },
            ondestroy: function (action) {
                //var iframe = this.getIFrameEl();

                grid.reload();

            }
        });

    } else {
        mini.showTips({
            content: "请选择一条记录",
            state: 'danger',
            x: 'Center',
            y: 'Top',
            timeout: 2000
        });
    }

}

//添加
function add() {
    mini.open({
        targetWindow: window,

        url: BaseUrl() + "/admin/user/addUpdate.html",
        title: "创建用户", width: 600, height: 400,
        onload: function () {
            var iframe = this.getIFrameEl();
            var data = { action: "add" };
            iframe.contentWindow.SetData(data);
        },
        ondestroy: function (action) {
            grid.reload();
        }
    });
}

//删除
function remove() {
    var rows = grid.getSelecteds();
    if (rows.length == 0) {
        mini.showTips({
            content: "请选择一条记录",
            state: 'danger',
            x: 'Center',
            y: 'Top',
            timeout: 2000
        });
    } else {
        mini.confirm("确定删除？", "确定？",
            function (action) {
                if (action == "ok") {
                    var uuids = [];
                    for (var i = 0; i < rows.length; i++) {
                        uuids.push(rows[i].uuid);
                    }

                    $.ajax({
                        url: GatewayUrl() + '/user/delete',
                        type: 'post',
                        contentType: "application/json",
                        data: JSON.stringify(uuids),
                        headers: {
                            "Authorization": localStorage.getItem("token")
                        },
                        success: function (dt) {
                            if (dt.code === 200) {
                                refresh('删除成功');
                            }
                        }
                    })
                }
            }
        );
    }
}

//自定义单元格内容、样式
grid.on("drawcell", function (e) {
    var record = e.record,
        column = e.column,
        field = e.field,
        value = e.value;


    //年龄    
    if (field == 'age') {
        e.cellHtml = value + "岁";
    }

    //将性别文本替换成图片
    if (field == "sex") {
        if (e.value == 1) {
            e.cellHtml = "<span class='icon-boy'></span>"
        } else {
            e.cellHtml = "<span class='icon-female'></span>"
        }
    }

    //状态
    if (field == "status") {
        if (e.value == 1) {
            e.cellHtml = "启用";
            e.cellStyle = "color:green;font-weight:bold;";
        } else {
            e.cellHtml = "停用";
            e.cellStyle = "color:red;font-weight:bold;";
        }
    }


})